package com.apex.sdk.ui;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.Messenger;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.apex.bluetooth.callback.GeneralCallback;
import com.apex.bluetooth.callback.OtaCallback;
import com.apex.bluetooth.core.EABleManager;
import com.apex.bluetooth.enumeration.EABleConnectState;
import com.apex.bluetooth.model.EABleCustom707Dial;
import com.apex.bluetooth.model.EABleOta;
import com.apex.bluetooth.model.EABleWatchInfo;
import com.apex.bluetooth.utils.LogUtils;
import com.apex.lie_sheng_jie.watcha.JieliDialCallback;
import com.apex.lie_sheng_jie.watcha.JieliWatchFaceManager;
import com.apex.lie_sheng_jie.watcha.JieliWatchInfo;
import com.apex.sdk.R;
import com.apex.sdk.databinding.ActivityJieliCustomDialBinding;
import com.apex.sdk.dialog.DialSelectPicDialog;
import com.apex.sdk.dialog.WaitingDialog;
import com.apex.sdk.model.WatchInfo;
import com.bumptech.glide.Glide;
import com.jieli.bmp_convert.BmpConvert;
import com.jieli.bmp_convert.OnConvertListener;
import com.jieli.jl_fatfs.model.FatFile;
import com.jieli.jl_rcsp.interfaces.watch.OnWatchOpCallback;
import com.jieli.jl_rcsp.model.base.BaseError;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class JieliCustomDialActivity extends AppCompatActivity {
    final String TAG = this.getClass().getName();
    ActivityJieliCustomDialBinding activityJieliCustomDialBinding;
    private DialSelectPicDialog dialSelectPicDialog;
    int[] style = new int[]{R.mipmap.jieli_watchface_no, R.mipmap.jieli_watchface_1, R.mipmap.jieli_watchface_2, R.mipmap.jieli_watchface_3, R.mipmap.jieli_watchface_4};
    int dialStyle;//表盘风格，0 无风格，  1 时间风格，  2 指针风格
    int realStyle;//真实对应风格

    int styleColor = 0;
    private final int PERMISSION_CODE = 3;
    private final int IMAGE_REQUEST_CODE = 0;
    private final int CAMERA_REQUEST_CODE = 1;
    private WaitingDialog waitingDialog;
    private final String DIAL_BG = "dial_bg.png";
    private Uri imageUri;
    private String backBitmap;
    private WatchInfo watchInfo;
    int imageTransState;//0,未传输，1，传输失败，2.传输成功
    Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0x53) {

                if (waitingDialog != null && waitingDialog.isShowing()) {
                    waitingDialog.dismiss();
                }
                imageTransState = 2;
                Toast.makeText(JieliCustomDialActivity.this, getString(R.string.ota_success), Toast.LENGTH_SHORT).show();
            } else if (msg.what == 0x54) {

                if (waitingDialog != null && waitingDialog.isShowing()) {
                    waitingDialog.dismiss();
                }
                Toast.makeText(JieliCustomDialActivity.this, getString(R.string.ota_failed), Toast.LENGTH_SHORT).show();
            } else if (msg.what == 0x20) {

                if (!TextUtils.isEmpty(backBitmap)) {
                    File file = new File(backBitmap);
                    if (file.exists()) {
                        file.delete();
                    }
                }
                backBitmap = (String) msg.obj;
                Glide.with(JieliCustomDialActivity.this).load(backBitmap).into(activityJieliCustomDialBinding.backImage);

            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activityJieliCustomDialBinding = ActivityJieliCustomDialBinding.inflate(getLayoutInflater());
        setContentView(activityJieliCustomDialBinding.getRoot());
        activityJieliCustomDialBinding.tool.setNavigationIcon(R.mipmap.exit_page);
        setSupportActionBar(activityJieliCustomDialBinding.tool);
        getSupportActionBar().setTitle(null);
        watchInfo = (WatchInfo) getIntent().getSerializableExtra("param");
        activityJieliCustomDialBinding.tool.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(RecyclerView.HORIZONTAL);
        activityJieliCustomDialBinding.zodiacList.setLayoutManager(linearLayoutManager);
        //  Glide.with(this).load(style[selectStyle]).into(activityJieliCustomDialBinding.styleImage);
        activityJieliCustomDialBinding.selectBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
                    if (checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                        initDialog();
                    } else {
                        requestPermissions(new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_CODE);
                    }
                } else {
                    if (checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.READ_MEDIA_IMAGES) == PackageManager.PERMISSION_GRANTED) {
                        initDialog();
                    } else {
                        requestPermissions(new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_MEDIA_IMAGES}, PERMISSION_CODE);
                    }
                }
            }
        });
        activityJieliCustomDialBinding.install.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (waitingDialog == null) {
                    waitingDialog = new WaitingDialog(JieliCustomDialActivity.this);
                }
                if (!waitingDialog.isShowing()) {
                    waitingDialog.show();
                }
                //开始自定义表盘
                Log.i(TAG, "表盘地址：" + backBitmap);
                if (!TextUtils.isEmpty(backBitmap)) {
                    if (imageTransState != 2) {
                        EABleWatchInfo eaBleWatchInfo = new EABleWatchInfo();
                        eaBleWatchInfo.setLcd_full_h(watchInfo.lcd_full_h);
                        eaBleWatchInfo.setLcd_full_w(watchInfo.lcd_full_w);
                        eaBleWatchInfo.setLcd_full_type(watchInfo.lcd_full_type);
                        eaBleWatchInfo.setLcd_preview_h(watchInfo.lcd_preview_h);
                        eaBleWatchInfo.setLcd_preview_w(watchInfo.lcd_preview_w);
                        eaBleWatchInfo.setLcd_preview_radius(watchInfo.lcd_preview_radius);
                        JieliWatchFaceManager.getInstance().customDialBack(backBitmap, new OtaCallback() {
                            @Override
                            public void success() {
                                Log.i(TAG, "自定义表盘安装成功");
                                if (mHandler != null) {
                                    mHandler.sendEmptyMessage(0x53);
                                }

                            }

                            @Override
                            public void progress(int i) {
                                Log.i(TAG, "自定义表盘安装进度：" + i);

                            }

                            @Override
                            public void mutualFail(int i) {
                                Log.i(TAG, "自定义表盘安装失败：" + i);
                                if (mHandler != null) {
                                    mHandler.sendEmptyMessage(0x54);
                                }
                            }
                        }, eaBleWatchInfo, dialStyle, styleColor, realStyle);
                    } else {
                        JieliWatchFaceManager.getInstance().changeCustomDialStyle(dialStyle, styleColor, realStyle, new GeneralCallback() {
                            @Override
                            public void result(boolean b) {
                                if (mHandler != null) {
                                    mHandler.sendEmptyMessage(0x53);
                                }
                            }

                            @Override
                            public void mutualFail(int i) {
                                if (mHandler != null) {
                                    mHandler.sendEmptyMessage(0x54);
                                }
                            }
                        });
                    }
                } else {
                    JieliWatchFaceManager.getInstance().changeCustomDialStyle(dialStyle, styleColor, realStyle, new GeneralCallback() {
                        @Override
                        public void result(boolean b) {
                            if (mHandler != null) {
                                mHandler.sendEmptyMessage(0x53);
                            }
                        }

                        @Override
                        public void mutualFail(int i) {
                            if (mHandler != null) {
                                mHandler.sendEmptyMessage(0x54);
                            }
                        }
                    });
                }

            }
        });
        StyleAdapter styleAdapter = new StyleAdapter();
        activityJieliCustomDialBinding.zodiacList.setAdapter(styleAdapter);


    }

    int count;

    private void initDialog() {
        if (dialSelectPicDialog == null) {
            final DialSelectPicDialog.Builder builder = new DialSelectPicDialog.Builder(JieliCustomDialActivity.this);
            builder.setAlbumonButton(new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    Intent intent = new Intent(Intent.ACTION_PICK, null);
                    intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                    startActivityForResult(intent, IMAGE_REQUEST_CODE);
                    dialog.dismiss();
                }
            });
            builder.setPhotoButton(new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    if (hasSdcard()) {
                        File outputImage = new File(getExternalCacheDir(), DIAL_BG);
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                            imageUri = FileProvider.getUriForFile(JieliCustomDialActivity.this, getPackageName() + ".fileProvider", outputImage);
                        } else {
                            imageUri = Uri.fromFile(outputImage);
                        }
                        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                        startActivityForResult(intent, CAMERA_REQUEST_CODE);
                    } else {
                        Log.e(TAG, "外置SDK不存在");
                    }
                    dialog.dismiss();
                }
            });
            builder.setCancelButton(new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            dialSelectPicDialog = builder.create();
        }
        if (!dialSelectPicDialog.isShowing()) {
            dialSelectPicDialog.show();
        }
    }

    private boolean hasSdcard() {
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }

    class StyleAdapter extends RecyclerView.Adapter<StyleAdapter.StyleHold> {
        @NonNull
        @Override
        public StyleHold onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View childView = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_jieli_custom, parent, false);
            return new StyleHold(childView);
        }

        @Override
        public void onBindViewHolder(@NonNull StyleHold holder, int position) {
            if (style == null) {
                return;
            }
            Glide.with(JieliCustomDialActivity.this).load(style[position]).into(holder.styleView);
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (position != 0) {
                        Glide.with(JieliCustomDialActivity.this).load(style[position]).into(activityJieliCustomDialBinding.styleImage);
                    }
                    if (position == 1 || position == 2) {
                        if (count % 3 == 0) {
                            styleColor = Color.RED;
                        } else if (count % 3 == 1) {
                            styleColor = Color.BLUE;
                        } else if (count % 3 == 2) {
                            styleColor = Color.GREEN;
                        }
                        count++;
                        activityJieliCustomDialBinding.styleImage.setColorFilter(styleColor, PorterDuff.Mode.SRC_ATOP);
                    } else {
                        styleColor = 0;
                        activityJieliCustomDialBinding.styleImage.clearColorFilter();
                    }
                    if (position == 0) {
                        dialStyle = 0;
                        realStyle = 0;
                    } else if (position == 1 || position == 2) {
                        dialStyle = 1;
                        realStyle = position;
                    } else {
                        dialStyle = 2;
                        realStyle = position - 2;
                    }
                }
            });

        }

        @Override
        public int getItemCount() {
            return style == null ? 0 : style.length;
        }

        class StyleHold extends RecyclerView.ViewHolder {
            ImageView styleView;

            public StyleHold(@NonNull View itemView) {
                super(itemView);
                styleView = itemView.findViewById(R.id.styleImage);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        boolean hasPermission = true;
        for (int result : grantResults) {
            if (result != PackageManager.PERMISSION_GRANTED) {
                hasPermission = false;
                break;
            }
        }
        if (hasPermission) {
            initDialog();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (resultCode != RESULT_CANCELED) {

            switch (requestCode) {
                case IMAGE_REQUEST_CODE://
                    Log.e(TAG, "从相册获取图片并剪切");
                    startPhotoZoom(data.getData());
                    break;
                case CAMERA_REQUEST_CODE:
                    if (hasSdcard()) {
                        startPhotoZoom(Uri.fromFile(new File(getExternalCacheDir(), DIAL_BG)));
                    } else {
                        startPhotoZoom(Uri.fromFile(new File(getCacheDir(), DIAL_BG)));
                    }

                    break;
                case CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE:
                    CropImage.ActivityResult result = CropImage.getActivityResult(data);
                    Uri resultUri = result.getUri();
                    if (resultUri == null) {
                        return;
                    }

                    //将数据进行保存
                    new SaveBitmapData(resultUri).start();
                    imageTransState = 0;
                    break;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void startPhotoZoom(Uri uri) {

        CropImage.activity(uri)
                .setGuidelines(CropImageView.Guidelines.ON)
                .setRequestedSize(watchInfo.lcd_full_w, watchInfo.lcd_full_h, CropImageView.RequestSizeOptions.RESIZE_EXACT)//解决有些图片裁剪得出239*239而导致更换不了表盘背景的问题
                .setMinCropResultSize(watchInfo.lcd_full_w, watchInfo.lcd_full_h)
                .setAspectRatio(watchInfo.lcd_full_w, watchInfo.lcd_full_h)//根据手表屏幕长方形或正方形进行背景裁剪，避免背景图被拉伸
                .start(this);

    }


    @Override
    protected void onDestroy() {
        if (waitingDialog != null) {
            waitingDialog.dismiss();
            waitingDialog = null;
        }
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
            mHandler = null;
        }
        super.onDestroy();
    }

    class SaveBitmapData extends Thread {
        Uri mUri;

        public SaveBitmapData(Uri mUri) {
            this.mUri = mUri;

        }

        @Override
        public void run() {
            super.run();
            try {

                String mime = getContentResolver().getType(mUri);
                String mimeType;
                if (mime != null && mime.equalsIgnoreCase("image/jpeg")) {
                    mimeType = ".jpg";
                } else {
                    mimeType = ".png";
                }

                BitmapFactory.Options options2 = new BitmapFactory.Options();
                options2.inPreferredConfig = Bitmap.Config.ARGB_8888;
                String orPath = mUri.getPath();
                Bitmap bitmap = BitmapFactory.decodeFile(orPath, options2);
                Log.i(TAG, "屏幕形状：" + watchInfo.lcd_full_type + "，orPath:" + orPath);
                if (bitmap != null) {
                    Bitmap outBitmap = Bitmap.createBitmap(watchInfo.lcd_full_w, watchInfo.lcd_full_h, Bitmap.Config.ARGB_8888);
                    Canvas canvas = new Canvas(outBitmap);
                    Paint paint = new Paint();
                    paint.setAntiAlias(true);
                    Path path = new Path();
                    if (watchInfo.lcd_full_type == 1) {//表示圆形
                        int raduis = Math.min(watchInfo.lcd_full_w, watchInfo.lcd_full_h) / 2;
                        //   canvas.drawCircle(watchInfo.lcd_full_w / 2, watchInfo.lcd_full_h / 2, raduis, paint);
                        path.addCircle(watchInfo.lcd_full_w / 2, watchInfo.lcd_full_h / 2, raduis, Path.Direction.CW);
                        // canvas.clipPath(path);
                        canvas.drawPath(path, paint);
                        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
                    } else {
                        RectF rectF = new RectF(0, 0, watchInfo.lcd_full_w, watchInfo.lcd_full_h);
                        canvas.drawRoundRect(rectF, watchInfo.lcd_preview_radius, watchInfo.lcd_preview_radius, paint);
                        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
                    }
                    canvas.drawBitmap(bitmap, 0, 0, paint);

                    String outPath = getExternalCacheDir().getAbsolutePath() + "/" + System.currentTimeMillis() + mimeType;
                    File nFile = new File(outPath);
                    if (nFile.exists()) {
                        Log.i(TAG, "删除结果：" + nFile.delete());
                    }
                    nFile.createNewFile();
                    FileOutputStream stream = new FileOutputStream(outPath);
                    if (!TextUtils.isEmpty(mimeType) && mimeType.equalsIgnoreCase(".jpg")) {
                        outBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
                    } else {
                        outBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
                    }
                    stream.flush();
                    stream.close();
                    bitmap.recycle();
                    bitmap = null;
                    outBitmap.recycle();
                    outBitmap = null;
                    Log.i(TAG, "backBitmap:" + backBitmap);
                    if (mHandler != null) {
                        Message message = new Message();
                        message.what = 0x20;
                        message.obj = outPath;
                        mHandler.sendMessage(message);
                    }

                } else {
                    Log.i(TAG, "图片不存在");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
